package com.wdc.hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@SuppressWarnings("all")
public class E06Leetcode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        //1.先让数组排序
        Arrays.sort(nums);
        //a + b + c = 0
        //c = -a - b
        ArrayList<List<Integer>> result = new ArrayList<>();
        //2.让数组索引 nums[0] = a  nums[1] = b、 nums[len - 1] = c
        for (int i = 0; i < nums.length; i++) {
            //如果一来就大于零就没有在找的必要,直接返回
            if (nums[i] > 0 ){
                return result;
            }
            //对 a 的去重
            if (i > 0 && nums[i] == nums[i -1] ){
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            //3.先让 a 循环，如果大了就让 c-- 小了就让 b++  然后 a++
            while (left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0){
                    right--;
                }else if (sum < 0){
                    left++;
                }else {
                    result.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    //对 b 和 c 去重
                    while (right > left && nums[right] == nums[right - 1]) right--;
                    while (right > left && nums[left] == nums[left + 1]) left++;

                    right--;
                    left++;
                }

            }
        }
        return result;
    }
}
